import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:laos_mall/common/config/app_const.dart';
import 'package:laos_mall/common/style/app_style.dart';
import 'package:laos_mall/common/style/extension_util.dart';
import 'package:laos_mall/common/widght/image_widget.dart';
import 'package:laos_mall/common/widght/list_title_widget.dart';
import 'package:laos_mall/models/home/home_model.dart';
import 'package:laos_mall/pages/main/config.dart';
import '../../widgets/number_mall_widget.dart';
import '../mall_config.dart';
import '../product_detail/logic.dart';
import 'logic.dart';

class SkuPage extends StatelessWidget {
  SkuPage({Key? key,this.skuId,this.productId}): super(key: key){
    Get.put(SkuLogic(skuId: skuId,productId: productId));
    skuLogic = Get.find<SkuLogic>();
  }

  // final skuLogic = Get.put(SkuLogic());
  late final SkuLogic skuLogic;
  int? skuId;
  int? productId;
  @override
  Widget build(BuildContext context) {
    // final skuLogic = Get.find<SkuLogic>();
    return GetBuilder<SkuLogic>(builder: (logic2) {
      return Obx(() {
        return Align(
            alignment: Alignment.bottomCenter,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Stack(
                  children: [
                    ListTitleWidget(
                      paddingOfLeft: EdgeInsets.symmetric(horizontal: 20.w),
                      leading: ImageWidget(
                        url: logic2.thumbUrl.value,
                        width: 180.w,
                        height: 180.w,
                        fit: BoxFit.contain,
                      ),
                      title: Row(
                        crossAxisAlignment: CrossAxisAlignment.baseline,
                        textBaseline: TextBaseline.alphabetic,
                        children: [
                          Text("${Config.symbol}", style:  AppStyle.textStyle.copyWith(fontSize: 18.sp)),
                          Text("${skuLogic.price}",style: AppStyle.textStyle.copyWith(fontSize: 18.sp)).addExpand()
                        ],
                      ).addContainer(margin: EdgeInsets.only(top: 20.h)),
                      maxLeadingW: 180.w,
                      spaceTitleMid: 20.h,
                      subtitle:
                      Column(
                        // crossAxisAlignment: CrossAxisAlignment.baseline,
                        // textBaseline: TextBaseline.alphabetic,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("${skuLogic.skuModel.value?.sku_data.map((e) => e.name).toList().join("|")}",
                              style: AppStyle.subtitleLightStyle),
                          SizedBox(height: 8.h,),
                          Text("PREVIEW: ${skuLogic.skuModel.value?.sku_data.map((e) => e.value).toList().join("-")}",style: AppStyle.textStyle)
                          // ItemWidget(
                          //   prefixItem: "${skuLogic.price}",
                          //   titleStyle: TextStyle(
                          //       color: "#FD4454".toColor, fontSize: 20,fontWeight: FontWeight.bold),
                          //   space: 10,
                          //   suffixItem: Text("库存：${skuLogic.skuNum}"),
                          //   subtitleStyle: TextStyle(
                          //       fontSize: 14, color: "#999999".toColor),
                          // )
                        ],
                      ),
                      showArrow: false,
                      rowCrossAxisAlignment: CrossAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                    ).addPadding( EdgeInsets.only(top: 20.h, right: 12)),
                    Positioned(
                        top: 0,
                        right: 0,
                        width: 40,
                        height: 40,
                        child: CloseButton(
                          color: AppColor.textColor1,
                        ).addContainer(color: Colors.transparent)),
                  ],
                ).addContainer(height: 200.h),
                _buildSkuWidget().addContainer(color: Colors.transparent),
                _buildNumber(),
                _buildBottom()
              ],
            )
                .addContainer(color: Colors.white,padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight))
                .addSingleChildScrollView());
      });
    });
  }

  Widget _buildSkuWidget() {
    return ListView.builder(
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (_, index) {

        var title = skuLogic.model?.attr_list?.spe[index].attr_name ?? "Color";
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title ?? "",
                style: const TextStyle(fontSize: 16, color: Color(0xFF999999))),
            const SizedBox(
              height: 12,
            ),
            GridView.builder(physics: const NeverScrollableScrollPhysics(),padding: EdgeInsets.zero,gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 70.w,childAspectRatio: 70/26,crossAxisSpacing: 18.w,mainAxisSpacing: 14.h), itemBuilder: (_,subIndex){
              var skuName = skuLogic.model?.attr_list?.spe[index].attr_list[subIndex].attr_value;
              var skuItem = skuLogic.skuModel.value?.sku_data.firstWhereOrNull((element) => title == element.name);
              var valueArr = skuLogic.model?.attr_list?.spe[index].attr_list.map((e) => e.attr_value).toList();
              var getIndex = valueArr?.indexOf(skuItem?.value ?? "");
              var isSel = getIndex == subIndex ? true : false;

              return  Text(
                skuName ?? "",
                style: AppStyle.subtitleStyle.copyWith(color: isSel ? AppColor.white : AppColor.redColor),
              )
                  .addContainer(
                  color:
                  isSel ?
                  AppColor.primaryColor
                      : AppColor.transparent,
                  padding: const EdgeInsets.symmetric(
                      horizontal: 0, vertical: 0),
                  alignment: Alignment.center,
                  )
                  .addGestureTap(() {
                // skuLogic.selIndex = subIndex;
                skuLogic.setSkuOfValue(index, skuName!);

              });
            },itemCount: skuLogic.model?.attr_list?.spe[index].attr_list.length,shrinkWrap: true,).addContainer(color: Colors.transparent),
          ],
        ).addPadding(EdgeInsets.only(bottom: 12.h));
      },
      shrinkWrap: true,
      itemCount: skuLogic.model?.attr_list?.spe.length ?? 0,
      padding: EdgeInsets.zero,
    ).addPadding( EdgeInsets.symmetric(horizontal: 20.w)).addContainer(color: Colors.transparent);
  }

  _buildNumber() {
    return Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
       Text("数量", style: AppStyle.textStyle)
          .addPadding(EdgeInsets.symmetric(horizontal: 20.w)),
      const Spacer(),
      Obx(() {
        return NumberMallWidget(
          number: skuLogic.buyNum.value,
          onChanged: (value) {
            skuLogic.buyNum.value = value;
            var price = skuLogic.buyNum.value.toDouble() * (double.tryParse(skuLogic.skuModel.value?.sku_price ?? "0") ?? 0.0);
            skuLogic.price.value = price.toStringAsFixed(2);
            skuLogic.update();
          },
        ).addContainer(color: Colors.transparent);
      }),
    ]).addContainer(height: 45.h);
  }

  _buildBottom(){
    return Row(children: [
      AppButton.fullBtn(() {
        Get.back();
      }, "cancel".tr,style: AppButtonStyle.hollowBlack).addExpand(),
      AppButton.fullBtn(skuLogic.addOrder, "confirm".tr).addExpand(),
    ],);
  }
}
